package UI;

import action.UserAction;

import javax.swing.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.*;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

// 每次添加完新组件以后一定要加上this.getContentPane().add(组件名)!!
public class ChatUI extends JFrame implements MouseListener {
    //加载聊天记录
    static BufferedReader joiner;
    //与谁聊天
    String chat2Who ;
    //文本域
    JTextArea chatArea = new JTextArea();
    public static JTextArea sendArea = new JTextArea("在此输入框输入聊天内容...");
    //提交
    JButton jb1 = new JButton("提交");
    //返回主界面按钮
    JButton returnHome = new JButton("返回主页");


    public ChatUI(String name) throws IOException {
        WholeUI wholeUI = new WholeUI(this) {
            @Override
            protected void elseWindow(JFrame jFrame) {
                jFrame.setSize(800, 600);
                jFrame.setTitle("与" + name + "的聊天界面");

            }

        };
        // 设置聊天对象
        this.chat2Who = name;
        //加载聊天文本域
        loadChatText();
        //加载按钮
        loadChatButton();





        // 从本地文件读取聊天记录(每100ms调用一次)

        new Thread(() -> {
            try {

                // 读取本地文件
                if (chatKind(chat2Who)){
                    joiner = new BufferedReader(new InputStreamReader(new FileInputStream("documents/ChatBox/Friend/"+LoginUI.userNameText.getText()+"&"+chat2Who +".txt")));
                }else {
                    joiner = new BufferedReader(new InputStreamReader(new FileInputStream("documents/ChatBox/Group/"+ chat2Who+".txt")));
                }
                Thread.currentThread().sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            }
            while (true) {
                try {
                    reLoadChatArea();
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }).start();





    }

    private static String nowTime() {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();

        // 定义格式化器，只保留年、月、日、时和分
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

        // 格式化时间字符串
        return now.format(formatter);
    }


    //判断聊天对象是私聊还是群聊
    private boolean chatKind(String roomName){
        if (roomName.endsWith("群")||roomName.endsWith("群聊")||roomName.endsWith("组")||roomName.endsWith("班")||roomName.endsWith("团")) {
            return false;
        }else {
           return true;
        }
    }

    private void loadChatButton() {
        jb1.setBounds(550, 500, 100, 30);
        //给按钮绑定鼠标事件(implements MouseListener的原因)
        jb1.addMouseListener(this);
        this.getContentPane().add(jb1);
        returnHome.setBounds(550, 550, 100, 30);
        returnHome.addMouseListener(this);
        this.getContentPane().add(returnHome);
    }

    private void loadChatText() {
        //聊天的文本域
        chatArea.setLineWrap(true);              //设置文本域自动换行
        chatArea.setBounds(20, 10, 500, 300);
        this.getContentPane().add(chatArea);
        //发送的文本域
        sendArea.setLineWrap(true);
        sendArea.setBounds(20, 400, 500, 100);
        this.getContentPane().add(sendArea);

    }

    @Override
    public void mouseClicked(MouseEvent e) {
        if (e.getSource() == returnHome) {
            HomeUI homeUI = new HomeUI();
            this.dispose();
        }


        // 点击提交按钮就执行发送消息
        if (e.getSource() == jb1) {
            System.out.println("发送的消息是" + ChatUI.sendArea.getText());
            String sendStr = LoginUI.userNameText.getText() + "("+nowTime()+")说:" + ChatUI.sendArea.getText() + "\n";
            // 清空发送框
            ChatUI.sendArea.setText("");

            // 使用独立线程发送消息
            new Thread(() -> {
                try {
                    // 发送消息到服务端
                    if(chatKind(chat2Who)){
                        UserAction.sendMessage2User(LoginUI.userNameText.getText()+"&"+chat2Who,chat2Who+"&"+LoginUI.userNameText.getText(),sendStr);
                    }else {
                        UserAction.sendMessage2Group(chat2Who,sendStr);
                    }

                } catch (IOException ex) {
                    // 记录错误或向用户提示
                    System.err.println("发送消息失败: " + ex.getMessage());
                    SwingUtilities.invokeLater(() -> {
                        JOptionPane.showMessageDialog(this, "发送消息失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                    });
                }
            }).start();
        }


    }

    private void reLoadChatArea() throws IOException {
        //让当前线程等待100ms避免消息还没写进本地文件就从本地文件读取

        try {
            Thread.sleep(100);
        } catch (InterruptedException ex) {
            throw new RuntimeException(ex);
        }
        //清空文本框
        //chatArea.setText("");
        // 从本地文件读取聊天记录
        String str;
        while((str=joiner.readLine())!=null){
            System.out.println(str);
            chatArea.append(str+"\n");

        }


    }













    @Override
    public void mousePressed(MouseEvent e) {

    }

    @Override
    public void mouseReleased(MouseEvent e) {

    }

    @Override
    public void mouseEntered(MouseEvent e) {

    }

    @Override
    public void mouseExited(MouseEvent e) {

    }
}
